package com.gj.my_aop.aspect;

import com.gj.my_aop.annotation.CustomerLogAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class CustomerLogAspect {
    //创建一个切入点 pointcut往哪切
    @Around(value = "@annotation(com.gj.my_aop.annotation.CustomerLogAnnotation)")
    public Object getLogAndTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result = null;
        //获取方法签名
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取方法
        Method method = methodSignature.getMethod();
        //获取方法上注解
        CustomerLogAnnotation annotation = method.getAnnotation(CustomerLogAnnotation.class);
        //通过注解属性判定是否要增强
        if (annotation != null && annotation.enable()){
            //增强
            System.out.println("方法执行前日志："+method.getName());
            long startTime = System.currentTimeMillis();
            //主业务逻辑放行
            result = proceedingJoinPoint.proceed();
            long endTime = System.currentTimeMillis();

            System.out.println("统计耗时："+(endTime-startTime) + "毫秒");
            System.out.println("方法执行后日志："+annotation.value());
            return result;
        }else {
            //没有注解直接放行
            result = proceedingJoinPoint.proceed();
            return result;
        }
    }
}
